<!-- 招标采购申请 -->
<template>
  <view>
    <u-form
      :model="model"
      :rules="rules"
      ref="form"
      labelPosition="top"
      labelWidth="auto"
      :labelStyle="{
        fontSize: '14px',
        color: '#B2B2B2',
        lineHight: '20px'
      }"
    >
      <view class="basic-style">
        <view class="basic-title basic-border">基本信息</view>
        <u-form-item label="单据编号" prop="purchaseBill" required>
          <u--input v-model="model.purchaseBill" disabled></u--input>
        </u-form-item>
        <u-form-item label="申请人" prop="proposer" required>
          <h-select-person-input
            style="width: 100%"
            disabled
            v-model="model.proposer"
            placeholder="请选择申请人"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            objectField="model.proposer"
          ></h-select-person-input>
        </u-form-item>
        <u-form-item label="申请部门" prop="departId" required>
          <h-select-depart-input
            disabled
            v-model="model.departId"
            :departName="model.proposerDeptText"
            placeholder="请选择部门"
            border="surround"
            style="width: 100%"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            :title.sync="model.proposerDeptText"
          ></h-select-depart-input>
        </u-form-item>
        <u-form-item label="申请时间" required>
          <u--input v-model="model.createTime" disabled suffixIcon="calendar-fill" :suffixIconStyle="{color: '#B2B2B2'}" placeholder="请选择日期"></u--input>
        </u-form-item>

        <u-form-item label="关联项目" prop="projectId">
					
					<h-select-project-input
					  ref="projectSelect"
					  v-model="model.projectId"
					  style="width: 100%"
					  placeholder="请选择关联项目"
					  objectField="model.projectId"
					  border="surround"
						:proDisabled="true"
						:projectStatus="'2'"
					  suffixIcon="arrow-down-fill"
					  :suffixIconStyle="{ color: '#B2B2B2' }"
					></h-select-project-input>
        </u-form-item>
        <u-form-item label="采购总预算(元)" prop="projectBudget" required>
					<h-money-input disabled placeholder="请输入采购总预算" v-model="model.projectBudget"></h-money-input>
        </u-form-item>
        <u-form-item label="费用所属团队" prop="teamId" required>
          <h-select-team-input
            style="width: 100%"
            v-model="model.teamId"
            objectField="model.teamId"
            placeholder="请选择费用所属团队"
            border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{color: '#B2B2B2'}"
            :tdlx="3"
          />
        </u-form-item>
        <u-form-item label="付款方式" prop="payManner" required>
          <u--input placeholder="请输入付款方式" v-model="model.payManner"></u--input>
        </u-form-item>
        <u-form-item label="采购大类" prop="provisionBroadType" required>
          <h-select-input-tag
            class="w-100"
            v-model="model.provisionBroadType"
            objectField="model.provisionBroadType"
            placeholder="请选择采购大类"
            border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{color: '#B2B2B2'}"
            dictName="provision_broad_type"
						@change="isHideBusinessSegment"
          ></h-select-input-tag>
        </u-form-item>
        <u-form-item label="采购方式" prop="invitationManner" required>
          <h-select-input-tag
            class="w-100"
            v-model="model.invitationManner"
            objectField="model.invitationManner"
            placeholder="请选择采购方式"
            border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{color: '#B2B2B2'}"
            dictName="bidding_type"
          ></h-select-input-tag>
        </u-form-item>
        <u-form-item label="物料类别" prop="provisionBroad" required>
          <h-dropdown
            class="w-100"
            keyName="categoryName"
            placeholder="请选择物料类别"
            :api="api.queryProvisionBroadList"
            v-model="model.provisionBroad"
            dataKey="result"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{color: '#B2B2B2'}"
            @change="checkSwitch('provisionBroad', null, $event)"
          />
        </u-form-item>
        <u-form-item label="所属业务板块" prop="businessSegment" required v-if="showBusinessSegment">
          <h-select-input-tag
            class="w-100"
            v-model="model.businessSegment"
            objectField="model.businessSegment"
            placeholder="请选择所属业务板块"
            border="surround"
            						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{color: '#B2B2B2'}"
            dictName="business_segment"
          ></h-select-input-tag>
        </u-form-item>
        <u-form-item label="期望到货时间" prop="expectUseTime" required>
          <h-time-select
            mode="datetime"
            ref="remittanceDate"
            v-model="model.expectUseTime"
            placeholder="请选择期望到货时间"
            border="surround"
            suffixIcon="calendar-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-time-select>
        </u-form-item>
        <u-form-item label="采购需求及项目描述" prop="description" required>
					<u--textarea :confirm-type="null" v-model="model.description" :maxlength="30" count placeholder="请输入采购需求及项目描述"></u--textarea>
        </u-form-item>
        <u-form-item label="备注" prop="remark">
          <u--textarea :confirm-type="null" v-model="model.remark" count :maxlength="500" placeholder="请输入备注"></u--textarea>
        </u-form-item>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border pt-1">物料明细</view>
        <view class="space-y-1 py-1">
          <u-button size="small" type="primary" @click="handleAddMaterial">新增</u-button>
        </view>

        <u-collapse>
          <u-collapse-item :title="item.materialName_dictText" v-for="(item, index) in formData" :key="index">
            <FormInfo
              :provisionBroad="model.provisionBroad" 
              :item="item"
              :index="index"
              @edit="handleEditForm"
              @remove="handleRemoveForm"
              @copy="handleCopyForm"
            />
          </u-collapse-item>
        </u-collapse>
        <u-popup mode="bottom" :show="showFormModal" closeable :closeOnClickOverlay="false" :round="10" @close="closeFormModal" @open="openFormModal">
          <TenderMaterialForm
            ref="dataForm"
            :provisionBroad="model.provisionBroad"
            :index="index"
            @submit="handleFormSubmit"
            @close="showFormModal = false"
          />
        </u-popup>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border">附件信息</view>
        <view class="py-1 space-y-1" style="width: 100%">
          <view style="color: red">
            提示：（附件要求：1、业主盖章版合同；2、工程量清单；3、技术要求等），请等待附件上传完成，再点击保存，否则附件无法保存成功！
          </view>
          <h-upload-file v-model="model.purchaseFile" :isIcon="false"></h-upload-file>
          <file-list v-if="model.purchaseFile" v-model="model.purchaseFile" :isDelete="true"></file-list>
        </view>
      </view>
			<view class="space-x-1 px-1 btn_position">
				<u-button :disabled="isSubmit" type="primary" :plain="true" text="保存" @click="onDraft"></u-button>
				<u-button :disabled="isSubmit"  type="primary"  text="保存并提交" @click="onSubmit"></u-button>
			</view>
			<view style="height: 100rpx;"></view>
    </u-form>

    <u-modal
      :show="confirmModal"
      title="是否确认"
      :closeOnClickOverlay="true"
      :asyncClose="true"
      @cancel="handleConfirmModalCancel"
      @confirm="handleConfirmModalConfirm"
      showCancelButton
    >
      <view class="slot-content">
        <view>是否确认切换物料类别，此操作将会清空物料明细中已填写的所有信息？</view>
      </view>
    </u-modal>
		
		<u-toast ref="uToast"></u-toast>
		<ProcessNodeConfiguration ref="processConfig" @ok="onOk"></ProcessNodeConfiguration>
  </view>
</template>

<script>
import { mapState } from 'vuex'
import moment from 'moment'
import { gainBillNo, add, edit, info, queryByDepartment, queryProvisionBroadList, erpPurchaseApplyInvitationDetailList } from '@/api/purchase/ErpPurchaseApplyInvitationForm'

import fileList from '@/pages/synergy/components/fileList.vue'
import TenderMaterialForm from './components/TenderMaterialForm.vue'
import FormInfo from './components/TenderMaterialFormInfo.vue'
import ProcessNodeConfiguration from '@/components/ProcessNodeConfiguration/ProcessNodeConfiguration.vue' // 流程节点配置人员选择弹窗
export default {
  name: 'ErpOmcPayContractManagerForm',
  components: {
    fileList,
    TenderMaterialForm,
    FormInfo,
  },
  data() {
    return {
			isSubmit: false, // 控制按钮是否可以点击
      backUpProvisionBroad: '',
      showBusinessSegment: false, // 控制所属业务板块
      exportTeamId: '',
      flag: false,
      index: null,
      showFormModal: false,
      confirmModal: false,
      loading: false,
      id: '',
      exportWarehouseList: [],
      foldWarehouseList: [],
      basicForm: {},
      formData: [], // 物料明细
      api: {
        queryByDepartment,
        queryProvisionBroadList,
      },
      model: {
        // 基本信息 - 公用
        bpmBizTitle: '',
        purchaseBill: '',
        proposer: '',
        departId: '',
        createTime: '',
        projectId: '',
        projectBudget: '',
        teamId: '',
        payManner: '',
        invitationManner: '',
        businessSegment: '',
        expectUseTime: '',
        description: '',
        provisionBroadType:'',  // 采购大类
        remark: '',
        // 附件
        purchaseFile: null,
      },
			provisionBroadups: null,
			
      rules: {
				purchaseBill: [{ required: true, message: '请输入单据编号!', trigger: ['blur', 'change'] }],
				departId: [{ required: true, message: '请选择申请部门!', trigger: ['blur', 'change'] }],
				proposer: [{ required: true, message: '请选择申请人!', trigger: ['blur', 'change'] }],
				createTime: [{ required: true, message: '请选择申请时间!', trigger: ['blur', 'change'] }],
				provisionBroadType: [{ required: true, message: '请选择采购大类!', trigger: ['blur', 'change'] }],
				
				// 费用所属团队
        teamId: [{ required: true, message: '请选择团队!', trigger: ['change', 'blur'] }],
        // 项目预算
        // projectBudget: [{ required: true, message: '请输入项目预算!', trigger: ['change', 'blur'] }],
        // 付款方式
        payManner: [{ required: true, message: '请输入付款方式!', trigger: ['change', 'blur'] }],
        // 采购方式
        invitationManner: [{ required: true, message: '请选择采购方式!', trigger: ['change', 'blur'] }],
        // 期望到货时间
        expectUseTime: [{ required: true, message: '请选择期望到货时间!', trigger: ['change', ['change', 'blur']] }],
        // 物料类别
        provisionBroad: [{ required: true, message: '请选择物料类别!', trigger: ['change', 'blur'] }],
        // 采购需求及项目描述
        description: [{ required: true, message: '请输入采购需求及项目描述!', trigger: ['change', 'blur'] }],
        //所属业务板块
        businessSegment: [{ required: true, message: '请选择所属业务板块!', trigger: ['change', 'blur'] }],
      },
			
			//代码生成后需手动设置流程编码
			flowCode: 'onl_erp_purchase_apply_invitation',
			formUrl: '/erp/purchase/procurement/modules/ErpPurchaseApplyInvitationForm',
			beanName: 'erpPurchaseApplyInvitationServiceImpl',
			formUrlMobile: '/pages/synergy/erpPurchaseApplyInvitationList',
			processId: '1559851668106854401'
    }
  },
  onLoad({ id }) {
    this.id = id || ''
  },
  created() {
    if (this.id) {
      this.initInfo()
			this.initDataList()
    } else {
      this.initForm()
      this.initBillNo()
    }
    // this.initBuyerInfo()
  },
  computed: {
    ...mapState(['userInfo']),
  },
  methods: {
    /**
     * 弹窗点击确认
     */
    handleConfirmModalConfirm() {
			this.confirmModal = false
			this.provisionBroadups = this.model.provisionBroad
					// 清空子表数据
			this.formData = []
			this.$set(this.model,'purchaseBudgetAmount',null)
    },
    /**
     * 弹窗点击取消
     */
    handleConfirmModalCancel() {
      // 还原修改的数据
      this.confirmModal = false
      this.model.provisionBroad = this.provisionBroadups
    },
    /**
     * 修改值时，检查是否需要弹出对话框确认修改
     * 取消 modal 的时候，需要将值还原
     * @param {String} key BasicForm 中的key值
     * @param {Function} fn 回调函数
     * @param {any} data 回调函数参数
     */
    checkSwitch(key, fn, data) {
			if (!!this.model.provisionBroad && !!data) {
				// 判断采购大类是否变化
				if (this.provisionBroadups !== data) {
					let details = this.formData
					if (details.length > 0) {
						const that = this;
						this.confirmModal = true
					} else {
						this.provisionBroadups = data
					}
				}
			}
    },
		isHideBusinessSegment () {
			if(!!this.model.provisionBroadType&&this.model.provisionBroadType=='administration'){
				// 选择的是行政类
				this.showBusinessSegment = false;
				
			}else{
			// 选择的不是行政类
				this.showBusinessSegment = true;
			}
			this.$set(this.model,'businessSegment',null) //选择行政类置空业务板块
		},
    projectChange() {},
    handleChangeFoldTeamId(val, num = 0) {
      let v = val.id
      this.foldTeamIdChange(v, num)
    },
    /**
     * 调出团队 change 事件
     * @param {Object} row 选中的团队
     * @param {Boolean} edit false 时清空 warehouse 和 exprortWareHouse
     */
    foldTeamIdChange(id, edit) {
      if (this.model.exportTeamId == id) {
        this.$u.toast('调入团队不能和调出团队相同')
        this.$set(this.model, 'foldTeamId', null)
        this.$set(this.model, 'foldWarehouse', undefined)
        return false
      }
      queryByDepartment({ department: id }).then((res) => {
        if (res.success) {
          this.foldWarehouseList = []
          if (!edit) {
            this.$set(this.model, 'foldWarehouse', undefined)
          }
          const data = res.result.map((res) => {
            return { id: res.id, categoryName: res.storehouseName }
          })
          this.foldWarehouseList = [data]
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    // 新增物料
    handleAddMaterial() {
      if (!this.model.provisionBroad) {
        this.$u.toast('请先选择物料类别')
        return false
      }
      this.index = null
      this.showFormModal = true
    },
    handleChangeExportTeamId(v, num = 0) {
      if (v != this.exportTeamId) {
        this.exportTeamIdChange(v, num)
      }
      this.exportTeamId = this.model.exportTeamId
    },
    /**
     * 调出团队 change 事件
     * @param {Object} row 选中的团队
     * @param {Boolean} edit false 时清空 warehouse 和 exprortWareHouse
     */
    exportTeamIdChange(row, edit = false) {
      const id = row.id
      if (this.model.foldTeamId == id) {
        this.model.exportTeamId = this.exportTeamId
        this.$u.toast('调入团队不能和调出团队相同')
        return false
      }
      // 清空子表
      // this.$refs.cannibalizeDetailList.reset()
      this.warehouse = null
      queryByDepartment({ department: id }).then((res) => {
        if (res.success) {
          this.exportWarehouseList = []
          if (!edit) {
            this.$set(this.model, 'exportWarehouse', undefined)
            this.warehouse = null
          }
          const list = res.result.map((res) => {
            return { id: res.id, categoryName: res.storehouseName }
          })
          this.exportWarehouseList = [list]
        } else {
          this.$u.toast(res.message)
        }
      })
    },
    handleCopyForm([item, index]) {
      this.formData.push({
        ...item,
      })
      this.$u.toast('复制成功')
    },
    handleEditForm([item, index]) {
      this.basicForm = { ...item }
      this.index = index
      this.showFormModal = true
    },
    handleRemoveForm(item) {
      this.formData = this.formData.filter((i) => i !== item)
    },
    closeFormModal() {
      this.$refs.dataForm.reset()
      this.basicForm = {}
      this.index = null
      this.showFormModal = false
    },
    openFormModal() {
      this.$refs.dataForm.basicForm = this.basicForm
    },
    addForm() {
      this.index = null
      this.showFormModal = true
    },
    /**
     * 子表单新增点击确认
     */
    handleFormSubmit(data, materialDetail) {
      this.showFormModal = false
			materialDetail.map(value => {
				this.formData.push({
					provisionSmall: value.provisionSmall, // 采购小类
					provisionSmall_dictText: value.provisionSmall_dictText, // 采购小类
					materialBillId: value.materialBill, // 物料编码
					materialName: value.id, // 物料名称
					materialName_dictText: value.materialName, // 物料名称
					brand: value.brand, // 品牌
					specification: value.specification, // 规格型号
					referencePrice: value.referencePrice, // 参考价格
					unit: value.unit, // 单位
					unit_dictText: value.unit_dictText, // 单位
					amount: '', // 领用数量
					budgetAmount: '' // 预算价格
				})
			})
    },
    // 获取单据编号
    async initBillNo() {
      const res = await gainBillNo()
      this.model.purchaseBill = res.result
      this.model.bpmBizTitle = this.userInfo?.employee?.name + '-' + this.model.purchaseBill //标题
    },
    // 初始化新增需要的数据
    initForm() {
      this.model.proposer = this.userInfo.empId //当前登录人
      this.model.departId = this.userInfo.deptId //当前登录人部门
      this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss')
    },
		
		// 编辑查询详情
    async initInfo() {
      const response = await info({ id: this.id })
      const data = response?.result || {}
			this.model = Object.assign({}, data)
			if(!!this.model.provisionBroadType&&this.model.provisionBroadType=='administration'){
				// 选择的是行政类
				this.showBusinessSegment = false;
			}else{
				// 选择的不是行政类
				this.showBusinessSegment = true;
			}
			
			this.provisionBroadups = this.model.provisionBroad
    },
		async initDataList() {
			const response = await erpPurchaseApplyInvitationDetailList({ billId: this.id })
			const data = response.success?response.result : []
			this.formData = data
		},
    validateForm() {
      return this.$refs.form.validate().then(async () => {
				if (!this.formData.length) {
				  this.$u.toast('请添加物料明细信息！')
				  return Promise.reject('请添加物料明细信息！')
				}
				// 判断数据有没有填写数量或者预算价格
				var isAmount = this.formData.some(item => !item.amount);
				var isBudgetAmount = this.formData.some(item => item.budgetAmount === '' || item.budgetAmount === null);
				if (isAmount) {
					// 当为true说明有值领用数量没有填写
					this.$u.toast('请填写物料明细中的数量！');
					return Promise.reject('请填写物料明细中的数量！')
				}
				if (isBudgetAmount) {
					// 当为true说明有值领用用途没有填写
					this.$u.toast('请填写物料明细中的预算价格！');
					return Promise.reject('请填写物料明细中的预算价格！')
				}
        if (this.model.projectBudget < 10000) {
          this.$u.toast('当前采购总金额小于10000元，请走采购申请单！')
          return Promise.reject('当前采购总金额小于10000元，请走采购申请单！')
        }
        
        return Promise.resolve()
      })
    },
    async onSubmit() {
      await this.validateForm()
			this.isSubmit = true
      try {
        this.loading = true
				var url = ''
				if (this.id) {
					url = edit
				} else {
					url = add
				}
        const response = await url({
          ...this.model,
          detailList: this.formData,
        })
        this.$u.toast(response.message)
        if (response.success) {
        	var that = this
        	
					// 获取流程列表
						if (this.model.id) {
							this.getProcessList(this.model.id)
						} else {
						// 判断添加的时候是否有返回id值
							if (response.result) {
								this.getProcessList(response.result)
							}
						
						}
						this.$refs.uToast.show({
							message: response.message,
							type: 'default',
							complete () {
								// that.isSubmit = false
							}
						})
          }
      } finally {
        // this.loading = false
      }
    },
    async onDraft() {
      // await this.validateForm()
      this.isSubmit = true
      try {
        this.loading = true
      		var url = ''
      		if (this.id) {
      			url = edit
      		} else {
      			url = add
      		}
        const response = await url({
          ...this.model,
          detailList: this.formData,
        })
        if (response.success) {
					
					this.$refs.uToast.show({
						message: response.message,
						type: 'default',
						complete () {
							this.isSubmit = false
							if (getCurrentPages().length > 1) {
								uni.navigateBack()
							} else {
								uni.reLaunch({
									url: '/pages/home/home'
								})
							}
							
						}
					})
        }
      } finally {
        this.loading = false
      }
    },
		// 获取流程列表
		getProcessList (id) {
			if (this.isSubmit) {
				this.$refs.processConfig.showPopup = true
				this.$refs.processConfig.formUrl = this.formUrl
				this.$refs.processConfig.formUrlMobile = this.formUrlMobile
				this.$refs.processConfig.flowCode = this.flowCode
				this.$refs.processConfig.edit(id, this.processId, this.beanName)
			}
		},
		// 提交流程成功
		onOk () {
			this.$refs.uToast.show({
				message: '提交成功',
				type: 'success',
				complete () {
					if (getCurrentPages().length > 1) {
						uni.navigateBack()
					} else {
						uni.reLaunch({
							url: '/pages/home/home'
						})
					}
					
				}
			})
		}
  },
  watch: {
		formData: {
			handler(data) {
				if(data.length > 0) {
					let count = 0
					data.forEach((item, index) => {
						count = count + (Number(item.amount) * Number(item.budgetAmount))
					})
					this.$set(this.model,'projectBudget',count)
				} else {
					this.$set(this.model,'projectBudget',null)
				}
			},
			immediate: true,
			deep: true
		},
    'model.provisionBroad'(current, old) {
      if (old && current && old !== current) {
        this.backUpProvisionBroad = old
      }
    },
  },
}
</script>

<style scoped lang="scss">
@import url('@/assets/inputStyle.scss');
.trip-form-data {
  ::v-deep {
    .u-form-item__body {
      padding-top: 2px;
      padding-bottom: 2px;
    }
  }
}
.checkbox-item {
  display: flex;
  align-items: center;
}
</style>
